package com.helwen.tools;
import java.io.*;
import java.util.List;

import org.apache.poi.xwpf.usermodel.IBodyElement;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.junit.jupiter.api.Test;



/**
 * 读取word，  只是读取国标中的word固定文件。
 *
 * @author Christmas_G
 *
 */
public class WordRead {
    @Test
    public void readWord() throws FileNotFoundException, IOException {
        XWPFDocument document = new XWPFDocument(new FileInputStream("C:\\develop\\docs\\检验状态信息查询服务2.docx"));
        /*String x="/controlActProcess/subject/registrationRequest/subject1/assignedEntity/id/item/@root";
        String[] arr=x.split("/");
        for(String s:arr){
            System.out.println(""+s);
        }*/
        try {
            // 获取word中的所有段落与表格
            List<IBodyElement> elements = document.getBodyElements();
            String protocol="";
            for (IBodyElement element : elements) {
                // 段落
                if (element instanceof XWPFParagraph) {
                    protocol= getTableCellText((XWPFParagraph) element);
                }
                // 表格
                else if (element instanceof XWPFTable) {
                    getTabelText((XWPFTable) element,protocol);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            document.close();
        }
    }

    /**
     * 获取段落内容
     *
     * @param paragraph
     */
    private void getParagraphText(XWPFParagraph paragraph) {
        // 获取段落中所有内容
        List<XWPFRun> runs = paragraph.getRuns();
        if (runs.size() == 0) {
            System.out.println("按了回车（新段落）222222");
            return;
        }
        StringBuffer runText = new StringBuffer();
        for (XWPFRun run : runs) {
            runText.append(run.text());
        }
        if (runText.length() > 0) {
            runText.append("，对齐方式222222：").append(paragraph.getAlignment().name());
            System.out.println(runText);
        }
    }

    private String getTableCellText(XWPFParagraph paragraph) {
        // 获取段落中所有内容
        List<XWPFRun> runs = paragraph.getRuns();
        if (runs.size() == 0) {
            System.out.println("按了回车（新段落）");
            return "";
        }
        StringBuffer runText = new StringBuffer();
        for (XWPFRun run : runs) {
            runText.append(run.text());
        }
        //System.out.println(runText);

        return runText.toString();
    }

    /**
     * 获取表格内容
     *
     * @param table
     */
    private void getTabelText(XWPFTable table,String protocol) throws Exception{
        List<XWPFTableRow> rows = table.getRows();
        File file=new File("C:\\develop\\docs\\result.txt");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        OutputStreamWriter osw = new OutputStreamWriter(fileOutputStream, "UTF-8");
        int x=0;
        for (XWPFTableRow row : rows) {
            if(x==0){
                x++;
                continue;
            }
            List<XWPFTableCell> cells = row.getTableCells();
            /*int i=0;
            for (XWPFTableCell cell : cells) {
                // 简单获取内容（简单方式是不能获取字体对齐方式的）
                // System.out.println(cell.getText());
                // 一个单元格可以理解为一个word文档，单元格里也可以加段落与表格
                List<XWPFParagraph> paragraphs = cell.getParagraphs();
                for (XWPFParagraph paragraph : paragraphs) {
                    getTableCellText(paragraph);
                }
            }*/
            //获取路径
            List<XWPFParagraph> paragraphs = cells.get(0).getParagraphs();//取第一个单元格中的值
            String path=getTableCellText(paragraphs.get(0));//
            if(protocol!=null && !protocol.equals("")){
                protocol=protocol.replace( " ",  "");
            }
            String xmlpath=protocol+path.replace( " ",  "");
            //获取注释
            List<XWPFParagraph> explans = cells.get(3).getParagraphs();//取第4个单元格中的值。
            String explain=getTableCellText(explans.get(0));//

            explain="<!--  "+explain +" -->";
            System.out.println(explain);

            String[] arr=xmlpath.split("/");
            int len=arr.length;
            String ll=arr[len-1];
            boolean isAttr=false;//是否是属性
            if(ll.startsWith("@")){
                ll=ll.substring(1);
                isAttr=true;
            }
            String name="";
            if(len>3){
                if(len<=4){
                    name=arr[len-2];
                }else if(len<=5){
                    name=arr[len-3]+getSpecificationWord(arr[len-2]);
                }else {
                    name=arr[len-4]+getSpecificationWord(arr[len-3])+getSpecificationWord(arr[len-2]);
                }

            }
            name=name+getSpecificationWord(ll);
            osw.write(explain+"\r\n");
            if(isAttr){
                xmlpath=xmlpath.substring(0,xmlpath.length()-ll.length()-2);
                String exXmlPlain="String "+name+" = doc.SelectSingleNode(\""+xmlpath+"\").Attributes[\""+ll+"\"].Value;\r\n";
                System.out.println(exXmlPlain);
                osw.write(exXmlPlain);
            }else{
                String exXmlPlain="<!--  上面是对元素的注释："+xmlpath+ "  -->";
                osw.write(exXmlPlain);
            }
            osw.flush();
        }
        osw.close();
        fileOutputStream.close();

    }

    private String getSpecificationWord(String word){
        if(word.length()>1){
            return word.substring(0, 1).toUpperCase()+word.substring(1);
        }else {
            return word;
        }
    }
}
